package com.dissertation.service.impl;

import com.dissertation.model.Assets;
import com.dissertation.pojo.Message;
import com.dissertation.respository.AssetsRepository;
import com.dissertation.service.ISaveAssetsService;
import com.dissertation.service.ITagCountService;
import com.dissertation.utils.AuthUtil;
import com.dissertation.utils.CompleteRateHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;

@Service
public class SaveAssetsImpl implements ISaveAssetsService {
    
    @Autowired
    AssetsRepository assetsRepository;

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    ITagCountService tagCountService;

    /**
     *
     * @param assets
     * @return
     * 需要先判断当前用户是否是第一作者
     * 需要更新tag的引用次数
     */
    @Override
    public Message save( Assets assets ) {

        Set<String> relative = new HashSet<>( assets.getParticipantNames() );
        relative.add( assets.getAuthor() );
        assets.setRelative( relative );
        assets.setUploader( AuthUtil.getUsername() );
        try {
            assets.setCompleteRate( CompleteRateHelper.getCompleteRate( assets ) );
        } catch ( IllegalAccessException e ) {
            throw new RuntimeException( e );
        }
        assets = assetsRepository.save( assets );
        final List<String> uniqueName = assets.getTag();

        CompletableFuture.supplyAsync( () -> tagCountService.updateCount( uniqueName, 1 ) )
                .thenRun( () -> tagCountService.updateStatus( uniqueName ) )
                .exceptionally( throwable -> {
                    throwable.printStackTrace();
            throw new RuntimeException( throwable );
        } );

        return Message.createSuc( assets.getId() );
    }

    @Override
    public Message update( Assets assets ) {
        String id = assets.getId();
        if ( id == null ) {
            return Message.createErr( "对不起，id不存在，不能进行更新" );
        }

        Assets oldAssets = assetsRepository.findOne( id );
        if ( oldAssets == null ) {
            return Message.createErr( "对不起，不存在id=" + id + "的数据" );
        }

        final List<String> uniqueName = oldAssets.getTag();
        CompletableFuture.supplyAsync( () -> tagCountService.updateCount( uniqueName, -1 ) )
                .exceptionally( throwable -> {
                    throwable.printStackTrace();
                    throw new RuntimeException( throwable );
                } );

        return save( assets );
    }



    
}
